package org.dousb.douojbackendjudgeservice.judge;


import cn.hutool.json.JSONUtil;
import org.dousb.douojbackend.common.common.ErrorCode;
import org.dousb.douojbackend.common.exception.BusinessException;
import org.dousb.douojbackend.model.codesandbox.ExecuteCodeRequest;
import org.dousb.douojbackend.model.codesandbox.ExecuteCodeResponse;
import org.dousb.douojbackend.model.codesandbox.JudgeInfo;
import org.dousb.douojbackend.model.dto.question.JudgeCase;
import org.dousb.douojbackend.model.entity.Question;
import org.dousb.douojbackend.model.entity.QuestionSubmit;
import org.dousb.douojbackend.model.enums.QuestionSubmitStatusEnum;
import org.dousb.douojbackendjudgeservice.judge.codesandbox.CodeSandbox;
import org.dousb.douojbackendjudgeservice.judge.codesandbox.CodeSandboxFactory;
import org.dousb.douojbackendjudgeservice.judge.codesandbox.CodeSandboxProxy;
import org.dousb.douojbackendjudgeservice.judge.strategy.JudgeContext;
import org.dousb.douojbackendserviceclient.service.QuestionFeignClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;


/**
 * JudgeServiceImpl
 *
 * @author 豆沙包
 * @version 1.0
 * @since 2025-11-01  15:43
 */
@Service
public class JudgeServiceImpl implements JudgeService {

    @Resource
    private QuestionFeignClient questionFeignClient;

    @Value("${codeSandbox.type:example}")
    private String type;

    @Resource
    private JudgeManager judgeManager;

    /**
     * 执行判题
     * 该方法用于对用户提交的代码进行判题，包括代码执行、结果比对、资源限制检查等步骤
     *
     * @param questionSubmitId 题目提交的唯一标识ID
     * @return 返回判题后的QuestionSubmit对象，包含判题结果和状态
     */
    @Override
    public QuestionSubmit doJudge(long questionSubmitId) {
        //1）传入题目的提交 id，获取到对应的题目、提交信息（包含代码、编程语言等）
        QuestionSubmit questionSubmit = questionFeignClient.getQuestionSubmitById(questionSubmitId);
        if (questionSubmit == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "提交信息不存在");
        }
        Long questionId = questionSubmit.getQuestionId();
        Question question = questionFeignClient.getQuestionById(questionId);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "题目不存在");
        }
        if (!questionSubmit.getStatus().equals(QuestionSubmitStatusEnum.WAITING.getValue())) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "题目正在判题");
        }
        QuestionSubmit questionSubmitUpdate = new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.RUNNING.getValue());
        boolean update = questionFeignClient.updateQuestionSubmitById(questionSubmitUpdate);
        if (!update) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "题目状态更新失败");
        }
        // 获取代码语言、代码内容和测试用例
        CodeSandbox codeSandbox = CodeSandboxFactory.createCodeSandbox(type);
        codeSandbox = new CodeSandboxProxy(codeSandbox);
        String language = questionSubmit.getLanguage();
        String code = questionSubmit.getCode();
        String judgeCaseStr = question.getJudgeCase();
        // 将测试用例字符串转换为JudgeCase对象列表
        List<JudgeCase> judgeCaseList = JSONUtil.toList(judgeCaseStr, JudgeCase.class);
        // 提取所有测试用例的输入，构建代码执行请求
        List<String> inputList = judgeCaseList.stream()
                .map(JudgeCase::getInput)
                .collect(Collectors.toList());
        // 构建代码执行请求对象
        ExecuteCodeRequest executeCodeRequest = ExecuteCodeRequest.builder()
                .code(code)
                .language(language)
                .inputList(inputList)
                .build();
        //执行代码沙箱，获取代码执行结果
        ExecuteCodeResponse executeCodeResponse = codeSandbox.executeCode(executeCodeRequest);

        List<String> outputList = executeCodeResponse.getOutputList();
        //2）根据沙箱执行结果 ，设置题目的判题状态和信息
        JudgeContext judgeContext = new JudgeContext();
        judgeContext.setJudgeInfo(executeCodeResponse.getJudgeInfo());
        judgeContext.setInputList(inputList);
        judgeContext.setOutputList(outputList);
        judgeContext.setJudgeCaseList(judgeCaseList);
        judgeContext.setQuestion(question);
        judgeContext.setQuestionSubmit(questionSubmit);
        //3）根据判题策略，执行判题逻辑，并返回判题结果
        JudgeInfo judgeInfo = judgeManager.doJudge(judgeContext);
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.SUCCEED.getValue());
        questionSubmitUpdate.setJudgeInfo(JSONUtil.toJsonStr(judgeInfo));
        update = questionFeignClient.updateQuestionSubmitById(questionSubmit);
        if (!update) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "题目更新失败");
        }
        QuestionSubmit questionSubmitResult = questionFeignClient.getQuestionSubmitById(questionId);
        return questionSubmitResult;
    }
}